package com.rslai.base.tool.servertest.database.datatype;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.dbunit.dataset.ITable;
import org.dbunit.dataset.datatype.AbstractDataType;
import org.dbunit.dataset.datatype.DataType;
import org.dbunit.dataset.datatype.TypeCastException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BitDataType extends AbstractDataType {
    public static final BitDataType TYPE = new BitDataType();

    private static final Logger logger = LoggerFactory.getLogger(BitDataType.class);

    private BitDataType() {
        super("BIT", -7, Integer.class, false);
    }

    public Object typeCast(Object value) throws TypeCastException {
        logger.debug("typeCast(value={}) - start", value);

        if ((value == null) || (value == ITable.NO_VALUE)) {
            return null;
        }

        if ((value instanceof Boolean)) {
            if (value.equals(Boolean.TRUE)) return Integer.valueOf(1);
            return Integer.valueOf(0);
        }

        if ((value instanceof Number)) {
            Number number = (Number) value;
            return Integer.valueOf(number.intValue());
        }

        if ((value instanceof String)) {
            String string = (String) value;

            if (string.equalsIgnoreCase("true"))
                return Integer.valueOf(1);
            if (string.equalsIgnoreCase("false")) {
                return Integer.valueOf(0);
            }
            return typeCast(DataType.INTEGER.typeCast(string));
        }

        throw new TypeCastException(value, this);
    }

    public void setSqlValue(Object value, int column, PreparedStatement statement) throws SQLException, TypeCastException {
        if (logger.isDebugEnabled()) {
            logger.debug("setSqlValue(value={}, column={}, statement={}) - start", new Object[]{value, new Integer(column), statement});
        }

        Object targetValue = typeCast(value);

        if (targetValue == null) {
            statement.setNull(column, -6);
        } else {
            Integer intValue = (Integer) targetValue;
            statement.setInt(column, intValue.intValue());
        }
    }
}
